from rest_framework import serializers
from apps.QuestionManagement.models import Questions
from .models import Paper, PaperQuestion
from ..QuestionManagement.serializers import QuestionsSerializer


class PaperQuestionSerializer(serializers.ModelSerializer):
    """试卷试题序列化器"""
    question = QuestionsSerializer()

    class Meta:
        model = PaperQuestion
        fields = ['question', 'score']


class PaperSerializer(serializers.ModelSerializer):
    """试卷列表序列化器"""
    created_user = serializers.StringRelatedField()
    updated_user = serializers.StringRelatedField()
    is_random = serializers.IntegerField(default=0)

    class Meta:
        model = Paper
        fields = ['id', 'exam_name', 'exam_description', 'exam_duration', 'total_score', 'status', 'created_user',
                  'created_at', 'updated_user', 'updated_at', 'is_random']

    def to_representation(self, instance):
        """转换布尔值为 0 和 1"""
        representation = super().to_representation(instance)
        representation['is_random'] = 1 if instance.is_random else 0
        return representation

    def to_internal_value(self, data):
        """转换 0 和 1 为布尔值"""
        if 'is_random' in data:
            data['is_random'] = True if data['is_random'] == 1 else False
        return super().to_internal_value(data)


class PaperDetailSerializer(serializers.ModelSerializer):
    """试卷详情序列化器，展示试题信息"""
    created_user = serializers.StringRelatedField()
    updated_user = serializers.StringRelatedField()
    questions = PaperQuestionSerializer(source='paperquestion_set', many=True)
    is_random = serializers.IntegerField(default=0)

    class Meta:
        model = Paper
        fields = ['id', 'exam_name', 'exam_description', 'exam_duration', 'total_score', 'status', 'created_user',
                  'created_at', 'updated_user', 'updated_at', 'questions', "is_random"]

    def to_representation(self, instance):
        """转换布尔值为 0 和 1"""
        representation = super().to_representation(instance)
        representation['is_random'] = 1 if instance.is_random else 0
        return representation

    def to_internal_value(self, data):
        """转换 0 和 1 为布尔值"""
        if 'is_random' in data:
            data['is_random'] = True if data['is_random'] == 1 else False
        return super().to_internal_value(data)


class PaperListSerializer(serializers.ModelSerializer):
    """试卷下拉框序列化器"""

    class Meta:
        model = Paper
        fields = ['id', 'exam_name', 'exam_duration']
